<template>
  <div class="productNameDoc">
    <div class="topbar">
      <p>编号</p>
      <el-input class="product_input1" v-model="no"></el-input>
      <p>品名</p>
      <el-input class="product_input1" v-model="name"></el-input>
      <p>执行标准</p>
      <el-input class="product_input1" v-model="norm"></el-input>
      <p>部类</p>
      <el-select
        v-model="typeId"
        key="pn_new1"
        @keyup.enter.native="blur()"
        clearable
        @clear="_getProductName"
      >
        <el-option
          v-for="item in typeIdList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
    </div>

    <div class="operation">
      <el-button type="primary" icon="el-icon-plus" @click="createPN"
        >新建部类</el-button
      >
      <el-button
        style="z-index: 2"
        @click="preservation"
        icon="el-icon-folder-checked"
        >保存</el-button
      >
      <!-- <el-button icon="el-icon-download">导入</el-button> -->
      <div class="dr">
        <i class="el-icon-download"></i>
        导入
        <input
          ref="upload"
          accept=".xls, .xlsx"
          class="outputlist_upload"
          type="file"
        />
      </div>
      <el-button @click="EXp" icon="el-icon-upload2">导出</el-button>
      <el-button @click="dele" icon="el-icon-delete">删除</el-button>
      <el-button type="primary" @click="_getProductName" icon="el-icon-search"
        >查询</el-button
      >
    </div>

    <el-table
      :data="productList"
      style="width: 100%"
      height="74vh"
      id="outTable"
      highlight-current-row
      :default-sort="{ prop: 'no', order: 'default-sort' }"
      :header-cell-style="{ background: '#f4f4f4', padding: 0, height: '40px' }"
      :cell-style="{ padding: 0, height: '36px' }"
      @row-click="rowClick"
    >
      <el-table-column prop="no" sortable label="编号"> </el-table-column>
      <el-table-column prop="name" label="品名"> </el-table-column>
      <el-table-column prop="norm" label="执行标准"> </el-table-column>
      <el-table-column prop="commodityTypeNo" label="部类"> </el-table-column>
    </el-table>

    <!-- 新建部类 -->
    <div class="mask" :style="{ display: isShowNew }"></div>

    <div class="newTypeId" :style="{ display: isShowNew }">
      <div class="newTop">
        <p>新建部类</p>
        <i class="el-icon-close" @click="closePN"></i>
      </div>

      <div class="newInfo">
        <p key="nifP1">部类</p>
        <el-input ref="inp1" v-model="newTypeId" key="pn_new0"></el-input>

        <p key="nifP2">名称</p>
        <el-input
          ref="inp2"
          v-model="newTypeName"
          key="pn_new2"
          @keyup.enter.native="savePN"
        ></el-input>
      </div>

      <el-table
        class="newTable"
        :data="typeIdName"
        highlight-current-row
        border
        height="330px"
        @row-click="typeClick"
        :header-cell-style="{
          background: '#f4f4f4',
          padding: 0,
          height: '40px'
        }"
        :cell-style="{ padding: 0, height: '36px' }"
      >
        <el-table-column prop="no" label="部类"> </el-table-column>
        <el-table-column prop="type" label="名称"> </el-table-column>
      </el-table>

      <div class="newBtn">
        <el-button size="small" @click="delPN">删除</el-button>
        <el-button size="small" type="primary" @click="savePN">保存</el-button>
      </div>
    </div>

    <foot-view
      class="footView"
      :pagesNum="pagesNum"
      :hasPagination="true"
      :pageSize="limit"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    >
      <div slot="text">
        <span>数据库：{{ jxQuarter }}</span>
      </div>
    </foot-view>
  </div>
</template>

<script>
import footView from '../../../components/FootView'
import {
  getProductName,
  postProductName,
  deleteProductName,
  putProductName,
  postExcelPname
} from '../../../network/productName'
import {
  getCommodityType,
  postCommodityType,
  putCommodityType,
  delCommodityType
} from '../../../network/commodity'
import enterUp from '../../../components/mixins/enterUp'
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
import outex from '../../../components/mixins/outexp'
// import axios from 'axios'
export default {
  name: 'productNameDoc',
  mixins: [enterUp, outex],
  created() {
    let jxQuarterVal = document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))
    this.jxQuarter = jxQuarterVal ? jxQuarterVal[1] : null
    
    this.inpList = this.getInput()
    this._getProductName()
    //获取部类信息
    this._getCommodityType()
    // 总条数，总页码赋值
    getProductName().then((res) => {
      // console.log(res.data.total)
      this.dataLen = res.data.data.length
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    })
  },
  data() {
    return {
      inpList: [],
      outputs: [],
      JList: [],
      // 总数据条数
      dataLen: 0,
      // 总页码
      pagesNum: 0,
      // 分页条数
      limit: 20,
      // 当前页码
      currentPage: 1,
      isShowNew: 'none',
      no: '',
      id: '',
      name: '',
      norm: '',
      typeId: '',
      allAlign: 'center',
      productList: [],
      typeIdList: [],
      typeIdName: [],
      delId: '',
      newTypeId: '',
      newTypeName: '',
      jxQuarter: null
      // jxQuarter: document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))[1]
    }
  },
  watch: {
    dataLen(a, b) {
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    },
    newTypeId(a, b) {
      let r = /^[A-Za-z]+$/
      if (!a || r.test(a)) {
        this.newTypeId = a.toUpperCase()
      } else {
        this.$message({
          type: 'warning',
          duration: 10,
          message: '部类请输入字母'
        })
        // this.$message.error('部类请输入字母')
        this.newTypeId = ''
        this.$refs.inp1.focus()
        return
      }
    }
  },
  components: {
    footView
  },
  methods: {
    EXp() {
      getProductName().then((res) => {
        this.productList = res.data.data
        this.$nextTick(() => {
          this.exp()
          this._getProductName()
        })
      })
    },
    InpFocus() {
      var pFocus = document.getElementById('input')
      pFocus.focus()
      pFocus.select()
    },

    _getProductName() {
      // let type = ''
      // for (const e of this.typeIdList) {
      //   if (e.value == this.typeId) {
      //     type = e.type
      //     break
      //   }
      // }
      let params = {
        limit: this.limit,
        page: this.currentPage,
        no: this.no,
        name: this.name,
        norm: this.norm,
        typeId: this.typeId
      }
      getProductName(params).then((res) => {
        this.productList = res.data.data.slice(
          (this.currentPage - 1) * this.limit,
          this.currentPage * this.limit
        )
        this.id = ''
        this.no = ''
        this.name = ''
        // this.norm = ''
        // this.typeId = ''
        if (this.productList.length == 0 && this.currentPage > 1) {
          this.currentPage--
          this._getArtNo()
        }
      })
    },
    _getCommodityType() {
      /*        *********************************************** 部类 */
      getCommodityType({ limit: 999, page: 1 }).then((res) => {
        this.typeIdList = []
        this.typeIdName = res.data.data || []
        if (this.typeIdName.length == 0) {
          postCommodityType({ no: 'A', type: '上衣' }).then(() => {
            this._getCommodityType()
          })
        }
        for (const i of this.typeIdName) {
          this.typeIdList.push({
            label: i.type,
            value: i.id,
            type: i.no
          })
        }
        this.newTypeId = ''
        this.newTypeName = ''
      })
    },
    preservation() {
      if (this.no == '' || this.name == '') {
        this.$message({
          type: 'warning',
          offset: 400,
          message: '编号和品名不能为空'
        })
        return
      }
      let obj = {
        no: this.no,
        name: this.name,
        norm: this.norm,
        typeId: Number(this.typeId)
      }

      for (const i of this.productList) {
        if (i.no == this.no) {
          obj.id = i.id
          this.$confirm('当前操作将修改此编号的数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            putProductName(obj).then((res) => {
              console.log(res)
              if (res.data.code == 200) {
                this._getProductName()
                this.$message({
                  type: 'success',
                  offset: 400,
                  message: '修改成功!'
                })
              }
            })
          })
          return
        }
        // return
      }
      postProductName(obj).then((res) => {
        console.log(res)
        if (res.data.code == 200) {
          this.dataLen++
          this._getProductName()
          this.$message({
            type: 'success',
            offset: 400,
            message: '添加成功!'
          })
        } else {
          this.$message.error({
            offset: 400,
            message: '添加失败 编号重复'
          })
        }
      })
    },

    dele() {
      if (this.id == '') {
        this.$message({
          type: 'warning',
          offset: 400,
          message: '请选择要删除的数据!'
        })
        return
      }
      let obj = { id: this.id }
      this.$confirm('是否删除此编号的数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteProductName(obj).then((res) => {
            console.log(res.data)
            if (res.data.code == 200) {
              this.$message({
                type: 'success',
                offset: 400,
                message: '删除成功!'
              })
              this.dataLen--
              this._getProductName()
            } else if (res.data.code == 204) {
              this.$message.error({
                offset: 400,
                message: '删除失败，该数据有关联数据!'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            offset: 400,
            message: '已取消删除'
          })
        })
    },

    createPN() {
      console.log(this.delId)
      this.isShowNew = 'block'
    },
    closePN() {
      this.isShowNew = 'none'
    },
    delPN() {
      if (this.delId == '') {
        this.$message({
          type: 'warning',
          offset: 400,
          message: '请选择要删除的数据!'
        })
        return
      } else {
        delCommodityType({ id: this.delId }).then((res) => {
          console.log(res.data)
          if (res.data.code == 200) {
            this.$message({
              type: 'success',
              offset: 400,
              message: '删除成功!'
            })
            this._getCommodityType()
          } else if (res.data.code == 204) {
            this.$message.error({
              message: '该数据有关联数据,删除失败'
            })
            this._getCommodityType()
          }
        })
      }
    },
    savePN() {
      // this.$refs.inp2.blur()

      let params = {
        id: this.delId,
        no: this.newTypeId,
        type: this.newTypeName
      }
      for (const i of this.typeIdName) {
        if (this.newTypeId == i.no) {
          this.$confirm(
            `此操作将修改部类编号为${this.newTypeId}的大类, 是否继续?`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
            .then(() => {
              putCommodityType(params).then((res) => {
                console.log(res)
                if (res.data.code == 200) {
                  this.$message({
                    type: 'success',
                    offset: 400,
                    message: '修改成功!'
                  })
                  this._getCommodityType()
                  this.$refs.inp1.focus()
                } else {
                  this.$message.error({
                    message: '修改失败',
                    offset: 400
                  })
                }
              })
            })
            .catch(() => {
              this.$message({
                type: 'info',
                offset: 400,
                message: '已取消修改'
              })
            })
          return
        }
      }

      postCommodityType(params).then((res) => {
        console.log(res)
        if (res.data.code == 200) {
          this.$message({
            message: '添加成功',
            offset: 400,
            type: 'success'
          })
          this._getCommodityType()
        }
      })
    },
    rowClick(e) {
      this.no = e.no
      this.id = e.id
      this.name = e.name
      this.norm = e.norm
      this.typeId = e.typeId
    },
    typeClick(e) {
      this.delId = e.id
      this.newTypeId = e.no
      this.newTypeName = e.type
    },

    readExcel(e) {
      //表格导入
      var that = this
      const files = e.target.files
      console.log(files)
      if (files.length <= 0) {
        //如果没有文件名
        return false
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$Message.error('上传格式不正确，请上传xls或者xlsx格式')
        return false
      }

      const fileReader = new FileReader()
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result
          console.log(data)
          const workbook = XLSX.read(data, {
            type: 'binary'
          })
          console.log(121, workbook)
          const wsname = workbook.SheetNames[0] //取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) //生成json表格内容
          console.log(ws)
          for (var a = 0; a < ws.length; a++) {
            this.JList.push(JSON.stringify(ws[a]))
          }
          console.log(this.JList)
          // let obj = {paramsList:ac,fieldMap:{brandedCompany:"123456"}}
          let obj = { paramsList: this.JList }
          console.log({ obj })

          postExcelPname(obj).then((res) => {
            console.log(res.data)
            if (res.data.code == 200) {
              this.$message({
                message: '导入成功',
                type: 'success'
              })
              this.JList = []
              this._getProductName()
            } else {
              this.$message({
                message: '导入失败，编号或品名重复',
                type: 'info'
              })
            }
          })

          that.outputs = [] //清空接收数据
          //编辑数据
          for (var i = 0; i < ws.length; i++) {
            var sheetData = {
              address: ws[i].addr,
              value: ws[i].value
            }
            that.outputs.push(sheetData)
          }
          this.$refs.upload.value = ''
        } catch (e) {
          return false
        }
      }
      fileReader.readAsBinaryString(files[0])
    },

    // 每页显示页数改变
    handleSizeChange(val) {
      this.limit = val
      // 总页码赋值
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
      this._getProductName()
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this._getProductName()
    }
  },
  mounted() {
    this.$refs.upload.addEventListener('change', (e) => {
      //绑定监听表格导入事件
      this.readExcel(e)
    })
  }
}
</script>

<style scoped>
.productNameDoc {
  margin-right: 15px;
  padding: 0 15px;
  background-color: white;
  height: 95vh;
  position: relative;
}
/* 头部 */
.topbar {
  height: 60px;
  display: flex;
  white-space: nowrap;
  border-bottom: 2px solid #f4f4f4;
}
.topbar p {
  width: auto;
  line-height: 60px;
}

/* 按钮 */
.operation {
  padding: 15px 0;
  white-space: nowrap;
  display: flex;
}

/* 新建部类 */
.mask {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  opacity: 0.3;
  z-index: 9;
}
.newTypeId {
  position: fixed;
  top: 25%;
  left: 50%;
  transform: translateX(-50%);
  width: 310px;
  height: 500px;
  z-index: 99;
  background-color: white;
  box-sizing: border-box;
}
.newTypeId .newTop {
  height: 40px;
  background-color: #f2f2f2;
}
.newTypeId .newTop p {
  float: left;
  line-height: 40px;
  padding-left: 20px;
}
.newTypeId .newTop i {
  float: right;
  line-height: 40px;
  padding: 0 16px;
}
.newTypeId .newInfo {
  display: flex;
}
.newTypeId .newInfo p {
  display: inline-block;
  width: 40px;
  line-height: 57px;
  margin-left: 15px;
}
.newTable {
  width: 280px;
  margin: 10px 15px;
}
.newBtn {
  position: absolute;
  bottom: 0;
  right: 0;
  margin-bottom: 20px;
}
.product_input1 {
  width: 160px;
  margin: 14px 25px 0 10px;
}

.footView span {
  float: left;
  margin-right: 48px;
  line-height: 6vh;
  font-size: 14px;
}
/* .dr{
    width: 75px;
    height: 30px;
    border: 1px solid #d7dae2;
    border-radius: 4px;
    position: relative;
    color: #606266;
    text-align: center;
    font-size: 14px;
    padding: 3px 0 0 0;
    margin-right: 15px;
  }
  .dr:hover{
    color: #017AFF;
    border-color: rgb(179, 215, 255);
    background-color: rgb(230, 242, 255);
    cursor:pointer;
  }
  .outputlist_upload{
    opacity: 0;
    position: absolute;
    left: -80px;
    overflow: hidden;
    width: 155px;
    cursor:pointer;
    height: 27px;
  } */
</style>

<style>
.productNameDoc .el-input__inner {
  height: 32px;
}
.productNameDoc .el-input__icon {
  line-height: 30px;
}
.productNameDoc .topbar .el-select {
  margin: 14px 25px 0 10px;
}

.productNameDoc .el-button {
  padding: 8px 15px;
  margin-right: 12px;
  height: 30px;
}
.productNameDoc .el-button + .el-button {
  margin-left: 0;
}

.productNameDoc .newTypeId .el-input {
  margin: 14px 0 0 0;
  width: 92px;
}
</style>
